#!/bin/bash

# MQTT本地测试脚本
# 使用本地mosquitto代理进行测试

echo "=== MQTT本地测试环境设置 ==="

# 检查mosquitto是否已安装
if ! command -v mosquitto >/dev/null 2>&1; then
    echo "❌ mosquitto未安装，正在安装..."
    sudo apt-get update
    sudo apt-get install -y mosquitto mosquitto-clients
    
    if [ $? -eq 0 ]; then
        echo "✅ mosquitto安装完成"
    else
        echo "❌ mosquitto安装失败"
        exit 1
    fi
else
    echo "✅ mosquitto已安装"
fi

# 启动本地mosquitto代理
echo "启动本地MQTT代理..."
mosquitto -v &
MOSQUITTO_PID=$!

# 等待代理启动
sleep 2

# 检查代理是否运行
if ps -p $MOSQUITTO_PID > /dev/null; then
    echo "✅ 本地MQTT代理启动成功 (PID: $MOSQUITTO_PID)"
else
    echo "❌ 本地MQTT代理启动失败"
    exit 1
fi

# 测试本地连接
echo "测试本地MQTT连接..."
timeout 3 bash -c "</dev/tcp/localhost/1883" > /dev/null 2>&1
if [ $? -eq 0 ]; then
    echo "✅ 本地MQTT端口可访问"
else
    echo "❌ 本地MQTT端口不可访问"
    kill $MOSQUITTO_PID 2>/dev/null
    exit 1
fi

echo ""
echo "=== 本地测试说明 ==="
echo "1. 修改mqtt_config.h中的MQTT_BROKER_HOST为\"localhost\""
echo "2. 重新编译: make"
echo "3. 运行客户端: ./mqtt_client"
echo ""
echo "测试命令:"
echo "  发布消息: mosquitto_pub -h localhost -t \"device/command\" -m \"status\""
echo "  订阅消息: mosquitto_sub -h localhost -t \"device/+\""
echo ""
echo "停止本地代理: kill $MOSQUITTO_PID"
echo "或者运行: pkill mosquitto"

# 等待用户操作
echo ""
read -p "按回车键停止本地代理并退出..."

# 清理
kill $MOSQUITTO_PID 2>/dev/null
echo "本地MQTT代理已停止"